import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/comment/comment_alert.dart';
import 'package:xvideos/hj_utils/api_service/common_service.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/debug_log.dart';

import '../../../alert_business/video/share_video_dialog.dart';

///图集底部操作按钮组
class AlbumActionWidget extends StatefulWidget {
  final VideoModel? videoModel;
  final int currentIndex; //如果传-1，则不显示查看 '1/3'之类的数据
  final Function(int)? commentAction;

  AlbumActionWidget({Key? key, this.videoModel, this.currentIndex = 0, this.commentAction});

  @override
  State<AlbumActionWidget> createState() => _AlbumActionWidgetState();
}

class _AlbumActionWidgetState extends State<AlbumActionWidget> {
  bool isCollectNeting = false; //是否正在调用收藏接口
  VideoModel? get model => widget.videoModel;
  bool get showIndex => widget.currentIndex != -1;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 70,
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: showIndex ? 9 : 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildThumpUp(),
          _buildFunctionItemUI(
            'count_msg.png'.communityPath,
            model?.commentCount?.humanizeFormatDefault("评论") ?? '评论',
            callback: _commentEvent,
          ),
          _buildCollectItem(),
          _buildFunctionItemUI('share_path.png'.videoPath, "分享", callback: () {
            Get.dialog(ShareVideoDialog(videoModel: widget.videoModel), useSafeArea: false);
          }),
          if (showIndex) ...[
            Container(
              padding: EdgeInsets.symmetric(horizontal: 11, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${widget.currentIndex + 1}",
                    style: TextStyle(color: AppColors.actionRed, fontSize: 12),
                  ),
                  Text(
                    "/${model?.seriesCover?.length ?? 0}",
                    style: TextStyle(color: Color(0xff3D3D3D), fontSize: 12),
                  ),
                ],
              ),
            )
          ]
        ],
      ),
    );
  }

  //点赞
  Widget _buildThumpUp() {
    return LikeButton(
      size: 20,
      isLiked: model?.vidStatus?.hasLiked ?? false,
      circleColor: CircleColor(start: AppColors.actionRed, end: AppColors.actionRed),
      bubblesColor: BubblesColor(
        dotPrimaryColor: AppColors.actionRed,
        dotSecondaryColor: AppColors.actionRed,
      ),
      likeBuilder: (bool isLiked) {
        return Image.asset(
          isLiked ? 'video_liked.png'.videoPath : 'video_like_border.png'.videoPath,
          width: 20,
          height: 20,
          color: isLiked ? AppColors.actionRed : Color(0xff989898),
        );
      },
      likeCount: model?.likeCount ?? 0,
      countBuilder: (int? count, bool isLiked, String text) {
        var color = isLiked ? AppColors.actionRed : Color(0xff989898);
        Widget result;
        if (count == 0) {
          result = Text("点赞", style: TextStyle(color: color, fontSize: 12));
        } else
          result = Text(count?.humanizeFormat ?? "点赞", style: TextStyle(color: color, fontSize: 12));
        return result;
      },
      onTap: (isLiked) async {
        String type = 'PIC';
        String? objID = model?.id;
        bool hasLiked = model?.vidStatus?.hasLiked ?? false;
        try {
          if (hasLiked) {
            await CommonService.cancelLike(objID, type);
            model?.likeCount = (model?.likeCount ?? 1) - 1;
            model?.likeCount = max(0, model?.likeCount ?? 0);
            model?.vidStatus?.hasLiked = false;
            showToast("取消点赞");
          } else {
            await CommonService.sendLike(objID, type);
            model?.likeCount = (model?.likeCount ?? 0) + 1;
            model?.likeCount = max(0, model?.likeCount ?? 0);
            model?.vidStatus?.hasLiked = true;
            showToast("点赞成功");
          }
        } catch (e) {
          debugLog('changeTagStatus $e');
        }
        if (mounted) setState(() {});
        return !isLiked;
      },
    );
  }

  //分享
  Widget _buildFunctionItemUI(String imagePath, String title, {GestureTapCallback? callback}) {
    return InkWell(
      onTap: callback,
      child: Container(
        alignment: Alignment.center,
        child: Row(
          children: [
            Image.asset(imagePath, width: 20, color: Color(0xff989898)),
            3.sizeBoxW,
            Text(title, style: TextStyle(color: Color(0xff989898), fontSize: 12)),
          ],
        ),
      ),
    );
  }

  //收藏
  Widget _buildCollectItem() {
    bool isCollect = model?.vidStatus?.hasCollected ?? false;
    return LikeButton(
      size: 20,
      isLiked: isCollect,
      circleColor: CircleColor(start: AppColors.actionRed, end: AppColors.actionRed),
      bubblesColor: BubblesColor(
        dotPrimaryColor: AppColors.actionRed,
        dotSecondaryColor: AppColors.actionRed,
      ),
      likeBuilder: (bool isLiked) {
        return Image.asset(
          isLiked ? 'collect_red.png'.commonImgPath : 'collect_empty.png'.commonImgPath,
          width: 20,
          color: isLiked ? AppColors.actionRed : Color(0xff989898),
        );
      },
      likeCount: model?.collectCount ?? 0,
      countBuilder: (int? count, bool isLiked, String text) {
        var color = isLiked ? AppColors.actionRed : Color(0xff666666);
        Widget result;
        if (count == 0) {
          result = Text("收藏", style: TextStyle(color: color, fontSize: 14));
        } else
          result = Text(count?.humanizeFormat ?? '', style: TextStyle(color: color, fontSize: 14));
        return result;
      },
      onTap: (isLiked) async {
        String type = 'PIC';
        String? objID = model?.id;
        bool hasCollected = model?.vidStatus?.hasCollected ?? false;

        if (hasCollected) {
          final success = await MineService.postCollect(objID, type, false);
          if (success) {
            model?.collectCount = (model?.collectCount ?? 1) - 1;
            model?.vidStatus?.hasCollected = false;
            model?.collectCount = max(0, model?.collectCount ?? 0);
            showToast("已取消收藏");
          }
        } else {
          final success = await MineService.postCollect(objID, type, true);
          if (success) {
            model?.collectCount = (model?.collectCount ?? 0) + 1;
            model?.vidStatus?.hasCollected = true;
            model?.collectCount = max(0, model?.collectCount ?? 0);
            showToast("收藏成功");
          }
        }
        if (mounted) setState(() {});
        return !isLiked;
      },
    );
  }

  //评论操作
  void _commentEvent() async {
    showCommentDialog(model?.id ?? '');
  }
}
